<template>
  <div>
    <AxiomSearchToolbar :fields="searchFields" @search="handleSearch" />
    <AxiomToolbar>
      <AxiomButton type="primary" icon="Plus" @click="handleAdd">新增角色</AxiomButton>
      <AxiomButton
        type="danger"
        icon="Delete"
        :disabled="!selectedRows.length"
        @click="handleBatchDelete"
      >
        批量删除
      </AxiomButton>
    </AxiomToolbar>
    <AxiomDataTable
      ref="dataTableRef"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <template #status="{ row }">
        <AxiomSwitch
          :model-value="row.status === 1"
          :disabled="row.role_code === 'ADMIN'"
          @change="(newState) => handleStatusChange(row, newState)"
        />
      </template>
      <template #actions="{ row }">
        <AxiomButton type="primary" text icon="Edit" @click="handleEdit(row)">编辑</AxiomButton>
        <AxiomButton type="primary" text icon="Setting" @click="handleAssign(row)">分配权限</AxiomButton>
        <AxiomButton type="danger" text icon="Delete" @click="handleDelete(row)">删除</AxiomButton>
      </template>
    </AxiomDataTable>

    <!-- 新增/编辑角色的对话框 -->
    <RoleFormDialog
      :visible="formDialogVisible"
      :mode="dialogMode"
      :initial-data="currentRow"
      @close="formDialogVisible = false"
      @success="handleSuccess"
    />

    <!-- 分配权限的对话框 -->
    <AssignPermissionDialog
      :visible="assignDialogVisible"
      :role-data="currentRow"
      @close="assignDialogVisible = false"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from 'vue';
import {
  AxiomDataTable,
  AxiomButton,
  AxiomToolbar,
  AxiomSearchToolbar,
  AxiomSwitch,
} from 'axiom-view';
import {
  getRoleList,
  deleteRole,
  enableRole,
  disableRole,
  batchDeleteRoles,
} from '@/api/system/role';
import RoleFormDialog from './RoleFormDialog.vue';
import AssignPermissionDialog from './AssignPermissionDialog.vue';

const { notification, useConfirm } = inject('axiom-utils');
const { show: showConfirm } = useConfirm;

const loading = ref(false);
const tableData = ref([]);
const selectedRows = ref([]);
const dataTableRef = ref(null);
const searchQuery = reactive({});
const searchFields = ref([
  { model: 'role_name', label: '角色名称', type: 'input', placeholder: '请输入角色名称' },
  { model: 'role_code', label: '角色代码', type: 'input', placeholder: '请输入角色代码' },
]);

const columns = ref([
  { type: 'selection', width: 55 },
  { prop: 'role_name', label: '角色名称' },
  { prop: 'role_code', label: '角色标识' },
  { prop: 'description', label: '描述' },
  { prop: 'status', label: '状态', width: 100, slot: 'status' },
  { prop: 'actions', label: '操作', width: 220, slot: 'actions' },
]);

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

const formDialogVisible = ref(false);
const assignDialogVisible = ref(false);
const dialogMode = ref('add');
const currentRow = ref(null);

const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      ...searchQuery,
    };
    const response = await getRoleList(params);
    if (response && response.success && response.data) {
      tableData.value = response.data.items.map(role => ({
        ...role,
        status: Number(role.status)
      }));
      pagination.total = response.data.total;
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page) => {
  pagination.currentPage = page;
  fetchData();
};

const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  fetchData();
};

const handleSearch = (query) => {
  Object.keys(searchQuery).forEach(key => delete searchQuery[key]);
  Object.assign(searchQuery, query);
  pagination.currentPage = 1;
  fetchData();
};

const handleAdd = () => {
  dialogMode.value = 'add';
  // [修复] 设置为 null 而不是 {}，以便子组件能够正确识别“新增”模式并清空表单
  currentRow.value = null;
  formDialogVisible.value = true;
};

const handleEdit = (row) => {
  // [修复] 禁止编辑 ADMIN 角色
  if (row.role_code === 'ADMIN') {
    notification.warning({ title: '操作受限', message: '不允许编辑超级管理员角色。' });
    return;
  }
  dialogMode.value = 'edit';
  currentRow.value = { ...row };
  formDialogVisible.value = true;
};

const handleAssign = (row) => {
  // [修复] 禁止为 ADMIN 角色分配权限
  if (row.role_code === 'ADMIN') {
    notification.warning({ title: '操作受限', message: '超级管理员默认拥有所有权限，无需分配。' });
    return;
  }
  currentRow.value = { ...row };
  assignDialogVisible.value = true;
};

const handleDelete = async (row) => {
  // [修复] 禁止删除 ADMIN 角色
  if (row.role_code === 'ADMIN') {
    notification.warning({ title: '操作受限', message: '不允许删除超级管理员角色。' });
    return;
  }
  await showConfirm({
    title: '确认删除',
    content: `您确定要删除角色【${row.role_name}】吗？`,
    type: 'error',
    onConfirm: async () => {
      await deleteRole(row.id);
      notification.success({ title: '成功', message: '删除成功' });
      fetchData(); // 重新加载数据
    },
  });
};

const handleBatchDelete = async () => {
  if (!selectedRows.value.length) {
    notification.warning({ title: '提示', message: '请至少选择一个角色' });
    return;
  }

  const containsAdmin = selectedRows.value.some(row => row.role_code === 'ADMIN');
  if (containsAdmin) {
    notification.error({ title: '操作失败', message: '选中的角色中包含超级管理员，无法删除。' });
    return;
  }

  await showConfirm({
    title: '确认批量删除',
    content: `您确定要删除选中的 ${selectedRows.value.length} 个角色吗？此操作不可逆。`,
    type: 'error',
    onConfirm: async () => {
      const ids = selectedRows.value.map(row => row.id);
      await batchDeleteRoles(ids);
      notification.success({ title: '成功', message: '批量删除成功' });
      if (dataTableRef.value) {
        dataTableRef.value.clearSelection();
      }
      fetchData();
    }
  });
};

const handleStatusChange = async (row, newState) => {
  const originalStatus = row.status;
  row.status = newState ? 1 : 0;

  try {
    const action = newState ? enableRole : disableRole;
    await action(row.id);
    notification.success({ title: '成功', message: '状态更新成功' });
  } catch (error) {
    row.status = originalStatus;
    console.error('更新角色状态失败:', error);
  }
};

const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

const handleSuccess = (updatedData) => {
  formDialogVisible.value = false;
  assignDialogVisible.value = false;
  fetchData();
};

onMounted(() => {
  fetchData();
});
</script> 